<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="renderer" content="webkit">
<meta name="force-rendering" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<title>MAP</title>

<style>
#map {
  height: 100%;
}

html,body {
  height: 100%;
  margin: 0;
  padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="__STATIC__/plugins/jquery/jquery.min.js"></script>
<script src="__STATIC__/plugins/layer/layer.js"></script>

<script>
var callback = '{$Request.param.callback}';

// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
let map, infoWindow;

var key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

function initMap() {
  map = new google.maps.Map(document.getElementById("map"), {
    center: { lat:  3.148872, lng: 101.683810 },

    zoom: 13,
  });
  infoWindow = new google.maps.InfoWindow();

  const locationButton = document.createElement("button");

  locationButton.textContent = "Pan to Current Location";
  locationButton.classList.add("custom-map-control-button");
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton);
  locationButton.addEventListener("click", () => {
    // Try HTML5 geolocation.
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          };

          infoWindow.setPosition(pos);
          infoWindow.setContent("Location found.");
          infoWindow.open(map);
          map.setCenter(pos);
        },
        () => {
          handleLocationError(true, infoWindow, map.getCenter());
        }
      );
    } else {
      // Browser doesn't support Geolocation
      handleLocationError(false, infoWindow, map.getCenter());
    }
  });
  
    map.addListener('click', function(e) {
         console.log(e.latLng.lat(),e.latLng.lng());
         
          //根据经纬度获取 当前地理信息
            var latLngData = e.latLng.lat().toFixed(6)+','+e.latLng.lng().toFixed(6);
            console.log(latLngData)
            $.ajax({
                type:"post",
                url:"https://maps.googleapis.com/maps/api/geocode/json?latlng="+latLngData+"&key="+key,
                async:true,
                success:function(data){
                    console.log(data)
             
                    var result = {
                        lat : e.latLng.lat().toFixed(6),
                        lng : e.latLng.lng().toFixed(6),
                        province : '',
                        city : '',
                        district : '',
                        address : '',
                        content : data.plus_code.compound_code,
                        data: data
                    };
                   
                    
                    if(data.results.length > 0){
                        var j;
                        for(j in  data.results){
                             var i;
                             var address_components = data.results[j].address_components;
                             var types = data.results[j].types;
                               //有完整省市区，如中国大陆       
                              if(types.toString() == ['political','sublocality','sublocality_level_1'].toString() || types.toString()=== ['premise'].toString() || types.toString()=== ['route'].toString() || types.toString()=== ['establishment', 'point_of_interest', 'transit_station'].toString()){                      
                                 for( i in address_components){
                                    var item = address_components[i];                                 
                                    if( item.types.toString() === ['administrative_area_level_1','political'].toString()){
                                        result.province = item.long_name;                                
                                    }                                  
                                    if(item.types.toString() === ['locality','political'].toString()){                          
                                        result.city = item.long_name;                                
                                    }                                     
                                    if( item.types.toString() === ['political','sublocality','sublocality_level_1'].toString()){                
                                        result.district = item.long_name;                                
                                    }  
                                    if( item.types.toString() === ['route'].toString()){ 
                                        result.address +=  ' '+ item.long_name;                                
                                    }                                   
                                    if( item.types.toString() === ['street_number'].toString()){       
                                        result.address +=  ' ' +item.long_name;                                
                                    }   
                                }  
                                if(! result.city ){
                                     result.city  = result.province;
                                }
                                if(!result.district){
                                    result.district = "N/A";
                                }
                                result.content = data.results[j].formatted_address;
                                break;
                             
                             }
                             //无完整省市区
                             if(types.toString() == ['street_address'].toString()){                      
                                 for( i in address_components){
                                    var item = address_components[i];                                 
                                    if( item.types.toString() === ['administrative_area_level_1','political'].toString()){
                                        result.province = item.long_name;                                
                                    }                                  
                                    if(item.types.toString() === ['locality','political'].toString()){                          
                                        result.city = item.long_name;                                
                                    }                                     
                                    if( item.types.toString() === ['political','sublocality','sublocality_level_1'].toString()){                
                                        result.district = item.long_name;                                
                                    }  
                                    if( item.types.toString() === ['route'].toString()){ 
                                        result.address +=  ' '+ item.long_name;                                
                                    }                                   
                                    if( item.types.toString() === ['street_number'].toString()){       
                                        result.address +=  ' ' +item.long_name;                                
                                    }   
                                }  
                                if(! result.city ){
                                     result.city  = result.province;
                                }                                  
                                if(!result.district){
                                    result.district = "N/A";
                                }
                                result.content = data.results[j].formatted_address;
                                break;                             
                             }
                        }
                    }       
                    
                    if(!result.province  || !result.city  || !result.district ){
                        console.log(result);
                        layer.msg("此地点无法识别，请选择其他地点");
                        return;
                    }     
                    result.address  = $.trim(result.address );                    
                    var site = latLngData+'<br />'+  result.content ;
                    console.log('result',result)
                    layer.alert(site,{
                        title: '确定选择该坐标？'
                        ,btn: ['确定','取消'] //按钮
                        ,yes:function(){                          
                            window.locationdata = result;
                            window.close();
                            var index = parent.layer.getFrameIndex(window.name);  
                            parent.layer.close(index);//关闭当前页
                            parent.window[callback](result);
                        }                        
                    }); //弹出信息提示窗口
                }
            });
    });
  
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
  infoWindow.setPosition(pos);
  infoWindow.setContent(
    browserHasGeolocation
      ? "Error: The Geolocation service failed."
      : "Error: Your browser doesn't support geolocation."
  );
  infoWindow.open(map);
}
</script>
<script async src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCBB-FqnLK9SiU8eXXUfvBhPJC6xgFoWiM&callback=initMap" ></script>
</body>
</html>